import 'package:flutter/material.dart';

/// 基于 BigInt(按 10^scale 单位) 的数字滚动动画，避免 double 精度问题
class RollingNumberUnits extends StatefulWidget {
  final BigInt units; // 当前值（整数单位）
  final int scale; // 小数位数，对应 10^scale 单位
  final TextStyle style;
  final String prefix;
  final String suffix;
  final Duration duration;

  const RollingNumberUnits({
    super.key,
    required this.units,
    required this.scale,
    required this.style,
    this.prefix = '',
    this.suffix = '',
    this.duration = const Duration(milliseconds: 800),
  });

  @override
  State<RollingNumberUnits> createState() => _RollingNumberUnitsState();
}

class _RollingNumberUnitsState extends State<RollingNumberUnits>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late BigInt _startUnits;
  late BigInt _endUnits;
  late int _totalFrames;

  @override
  void initState() {
    super.initState();
    _startUnits = widget.units;
    _endUnits = widget.units;
    _controller = AnimationController(vsync: this, duration: widget.duration);
    _totalFrames = _estimateFrames(widget.duration);
    _controller.forward();
  }

  @override
  void didUpdateWidget(RollingNumberUnits oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.units != widget.units || oldWidget.scale != widget.scale) {
      _startUnits = _currentUnits();
      _endUnits = widget.units;
      _totalFrames = _estimateFrames(widget.duration);
      _controller.duration = widget.duration;
      _controller.reset();
      _controller.forward();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        final currentUnits = _currentUnits();
        final text = _formatUnits(
          currentUnits,
          widget.scale,
          prefix: widget.prefix,
          suffix: widget.suffix,
        );
        return Text(text, style: widget.style);
      },
    );
  }

  int _estimateFrames(Duration duration) {
    // 估算 60fps 帧数，至少 1 帧
    final frames = (duration.inMilliseconds * 60) ~/ 1000;
    return frames > 0 ? frames : 1;
  }

  BigInt _currentUnits() {
    if (_controller.isDismissed) return _startUnits;
    if (_controller.isCompleted) return _endUnits;
    final frame = (_controller.value * _totalFrames).floor();
    final delta = _endUnits - _startUnits;
    // 线性插值：start + (delta * frame) / totalFrames，纯整数算术
    final progressed =
        (delta * BigInt.from(frame)) ~/ BigInt.from(_totalFrames);
    return _startUnits + progressed;
  }

  String _formatUnits(
    BigInt units,
    int scale, {
    String prefix = '',
    String suffix = '',
  }) {
    final isNegative = units.isNegative;
    BigInt absUnits = units.abs();
    final tenPow = BigInt.from(10).pow(scale);
    final integerPart = absUnits ~/ tenPow;
    final fractionalPart = (absUnits % tenPow).toString().padLeft(scale, '0');
    final sign = isNegative ? '-' : '';
    final body =
        scale == 0
            ? integerPart.toString()
            : '${integerPart.toString()}.$fractionalPart';
    return '$prefix$sign$body$suffix';
  }
}
